import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import moment from 'moment';
import { DATA_ENTRY, AdvancedSearch, NestedTableC, ContentPackage, PrimaryC } from '../../../comps';
import myStyle from './index.less';
import accounting from 'accounting';
import ShowModalC from './showModal';
import { findValueByCode } from '../../../utils/utils';

const FormItemLayout = {
  labelCol: {
    xs: { span: 4, offset: 0 },
    sm: { span: 8, offset: 0 },
    md: { span: 8, offset: 0 },
    lg: { span: 8, offset: 0 },
    xl: { span: 6, offset: 0 },
    xxl: { span: 5, offset: 0 },
  },
  wrapperCol: {
    xs: { span: 18, offset: 0 },
    sm: { span: 14, offset: 0 },
    md: { span: 14, offset: 0 },
    lg: { span: 14, offset: 0 },
    xl: { span: 17, offset: 0 },
    xxl: { span: 17, offset: 0 },
  },
};
@connect(({ CreditAccountDetailM, globalM, loading }) => ({
  CreditAccountDetailM,
  globalM,
  loading,
}))
@Form.create()
export default class CreditAccountDetailC extends PureComponent {
  state = {
    columns: undefined,
    dataSource: undefined, //
    columnsAdjust: undefined,
    currentPage: 1, // 页码
    numInPage: 20, // 每页条数
    currentPageAdujst: 1, // 页码 拆分
    pageInfo: {}, // 后端返回的页码信息
    searchObj: { startDate: moment(), endDate: moment() }, // 查询条件
    isReset: false, // 是否点击重置
    isShow: false, // 弹窗显示与否
    portfolioId: undefined, // 组合id
    columnsDefault: [
      { title: '交易时间', key: 'tradeTime', type: 'date', formatStr: 'YYYY-MM-DD HH:mm:ss' },
      { title: '产品名称', key: 'productName' },
      { title: '组合名称', key: 'portfolioName' },
      { title: '业务类型', key: 'businessType' },
      { title: '合约代码', key: 'tradingCode' },
      { title: '发生数量(手)', key: 'amount', type: 'number', toFixed: 0 },
      { title: '价格', key: 'price', type: 'money', toFixed: '2' },
      {
        title: '发生金额',
        key: 'totalPrice',
        type: 'money',
        toFixed: '2',
        render: (text, record) => {
          if (text === null || text === undefined) return '--';
          return (
            <div style={{ display: 'flex', float: 'right' }} className={record.typeColor}>
              {accounting.formatNumber(Number(text), 2)}
            </div>
          );
        },
      },
      {
        title: '处理前',
        key: 'before',
        children: [
          { title: '保证金余额', key: 'beforeRemainingSum', type: 'money', toFixed: '2' },
          { title: '保证金占用', key: 'beforeOccupy', type: 'money', toFixed: '2' },
          { title: '保证金可用', key: 'beforeAvailable', type: 'money', toFixed: '2' },
        ],
      },
      {
        title: '处理后',
        key: 'after',
        children: [
          { title: '保证金余额', key: 'afterRemainingSum', type: 'money', toFixed: '2' },
          { title: '保证金占用', key: 'afterOccupy', type: 'money', toFixed: '2' },
          {
            title: '保证金可用',
            key: 'afterAvailable',
            type: 'money',
            toFixed: '2',
            render: (text, record) => {
              if (text === null || text === undefined) return '--';
              return (
                <div style={{ display: 'flex', float: 'right' }} className={record.typeColor}>
                  {accounting.formatNumber(Number(text), 2)}
                </div>
              );
            },
          },
        ],
      },
    ],
    columnsChild: [
      // 子表
      { title: '业务类型', key: 'businessType' },
      { title: '合约代码', key: 'tradingCode' },
      {
        title: '发生金额',
        key: 'totalPrice',
        type: 'money',
        toFixed: '2',
        render: (text, record) => {
          if (text === null || text === undefined) return '--';
          return (
            <div style={{ display: 'flex', float: 'right' }} className={record.typeColor}>
              {accounting.formatNumber(Number(text), 2)}
            </div>
          );
        },
      },
    ],
  };

  componentDidMount() {
    this.queryTableList();
  }

  UNSAFE_componentWillReceiveProps(nextProps) {}

  // 查询列表
  queryTableList = () => {
    const {
      globalM: {
        dataDictionary: { FUTURE_CASHFLOW_TYPE = [] },
      },
    } = this.props;
    const { searchObj, portfolioId, isReset, numInPage, currentPage, columnsDefault, columnsChild } = this.state;
    if (isReset) {
      // 判断是否点击了重置 点击页码不进行后台查询
      message.warning('您已重置查询字段，请设置条件后执行查询');
      return;
    }

    this.setState({
      columns: undefined,
      dataSource: undefined, // 产品信息
      pageInfo: {},
    }); // 查询之前清除数据
    const params = {
      businessType: searchObj.businessType,
      portfolioId,
      startDate: searchObj.startDate ? searchObj.startDate.format('YYYY-MM-DD') : undefined,
      endDate: searchObj.endDate ? searchObj.endDate.format('YYYY-MM-DD') : undefined,
      currentPage,
      numInPage,
    };
    this.props.dispatch({
      type: 'CreditAccountDetailM/queryTableList',
      payload: {
        ...params,
      },
      callback: (data) => {
        if (data) {
          data.dataSource.map((item, key) => {
            item.productName = `${item.productCode}-${item.productName}`;
            item.portfolioName = `${item.portfolioCode}-${item.portfolioName}`;
            item.tradingCode = item.tradingCode ? `${item.tradingCode}-${item.tradingName}` : undefined;
            if (item.redOrGreen == 1) {
              item.typeColor = 'red';
            } // 颜色显示判断
            else if (item.redOrGreen == 2) {
              item.typeColor = 'green';
            } else {
              item.typeColor = '';
            }
            item.key = key;
            if (item.childData && item.childData.length) {
              item.childData.map((child, key) => {
                child.key = key;
                child.tradingCode = `${child.tradingCode}-${child.tradingName}`;
                child.typeColor = child.redOrGreen == 1 ? 'red' : child.redOrGreen == 2 ? 'green' : '';
              });
              columnsChild &&
                columnsChild.map((item) => {
                  if (item.key == 'businessType') {
                    item.render = (text, record) => {
                      if (text === null || text === undefined) return '--';
                      return <div className={record.typeColor}>{findValueByCode(text, FUTURE_CASHFLOW_TYPE)}</div>;
                    };
                  }
                });
              item.nestedConfig = {
                dataSource: item.childData,
                columns: columnsChild,
                scroll: { x: 800 },
                rowKey: 'key',
              };
            }
          });
          this.setState({
            columns: [...columnsDefault],
            dataSource: data.dataSource ? [...data.dataSource] : [],
            pageInfo: data.pageInfo || {},
          });
        } else {
          this.setState({
            columns: [...columnsDefault],
            dataSource: [],
            pageInfo: {},
          });
        }
      },
    });
  };

  // 组合变更
  portfolioChange = (e) => {
    let portfolioId;
    if (e) {
      portfolioId = [];
      e.info.map((item) => {
        portfolioId.push(item.portfolioCode);
      });
    }
    this.setState({ portfolioId });
  };

  // 表格页码排序改变调用
  handleTableChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
      },
      () => {
        this.queryTableList();
      },
    );
  };

  // 表格列表
  renderTable = () => {
    const { currentPage, numInPage, columns, dataSource, pageInfo } = this.state;
    const {
      globalM: {
        dataDictionary: { FUTURE_CASHFLOW_TYPE = [] },
      },
    } = this.props;
    columns &&
      columns.map((item) => {
        if (item.key == 'businessType') {
          item.render = (text, record) => {
            if (text === null || text === undefined) return '--';
            return <div className={record.typeColor}>{findValueByCode(text, FUTURE_CASHFLOW_TYPE)}</div>;
          };
        }
      });
    return (
      <div>
        <NestedTableC
          rowKey='key'
          onChange={this.handleTableChange}
          current={currentPage}
          total={pageInfo.total || 0}
          pageSize={numInPage}
          columns={columns}
          dataSource={dataSource}
          fixedChild={true}
          rowClassName={(record) => (record?.nestedConfig ? '' : myStyle.noExpend)} // 无子项 设置样式
          commonHeader={false}
        />
      </div>
    );
  };

  render() {
    const {
      globalM: {
        dataDictionary: { FUTURE_CASHFLOW_TYPE_QUERY = [] },
      },
    } = this.props;
    const searchProps = {
      dataSource: [
        {
          dataIndex: ['startDate', 'endDate'],
          title: '时间区间',
          type: DATA_ENTRY.RANGEDATE,
          initialValue: [moment(), moment()],
          formItemLayout: FormItemLayout,
          allowClear: true,
        },
        {
          dataIndex: 'portfolioId',
          title: '产品组合',
          type: DATA_ENTRY.PRODUCTGROUPTREE,
          onChange: this.portfolioChange,
          tradeModel: ['BOOKKEEPING_MODE', 'COMMAND_MODE', 'VALUATION_BOOKKEEPING_MODEL'], // 不支持选估值解析模式的产品
        },
        {
          dataIndex: 'businessType',
          title: '业务类型',
          type: DATA_ENTRY.SELECT,
          dataSource: FUTURE_CASHFLOW_TYPE_QUERY.map((item) => {
            return { value: item.code, title: item.value };
          }),
          allowClear: true,
        },
      ],
      onQuery: (e) => {
        if (e) {
          if (!(e.startDate && e.endDate)) {
            message.warning('日期区间不能为空');
            return;
          }
        }
        this.setState(
          {
            searchObj: e,
            currentPage: 1,
            isReset: false,
          },
          () => {
            this.queryTableList(); // 点击查询按钮
          },
        );
      },
      onClear: () => {
        // 点击重置按钮
        this.setState({
          searchObj: { startDate: moment(), endDate: moment() }, // 查询条件
          portfolioId: undefined,
          isReset: true,
        });
      },
      onRef: (ref) => {
        this.advancedSearch = ref;
      },
    };

    return (
      <ContentPackage
        title='信用账户资金明细'
        contentHtml={
          <div className={myStyle.credit}>
            <div>
              <AdvancedSearch {...searchProps} />
            </div>
            <PrimaryC
              title='当前保证金占用明细'
              style={{ marginTop: '20px', marginBottom: '16px' }}
              onClick={() => {
                this.setState({ isShow: true });
              }}
            />
            {this.renderTable()}
            {this.state.isShow && (
              <ShowModalC
                visible={this.state.isShow}
                visibleChange={(e) => {
                  this.setState({ isShow: e });
                }}
              />
            )}
          </div>
        }
      />
    );
  }
}
